package com.mashibing.juc.c_019;

import java.util.concurrent.Semaphore;

/**
 * @author: Yuanzt
 * @Date: 2021/3/29
 */
public class T11_TestSemaphore {
    public static void main(String[] args) {
        //参数表示允许多少个线程同时执行，线程不是平均分配，是抢占CPU资源
//        Semaphore s = new Semaphore(5);
        //fair参数可以设置是否公平
        Semaphore s = new Semaphore(5,true);

        /*new Thread(() -> {
            try {
                s.acquire();
                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 end!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();*/

        /*new Thread(() -> {
            try {
                s.acquire();
                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 end!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();*/

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    s.acquire();
                    System.out.println("T"+ finalI +"running...");
                    Thread.sleep(200);
                    System.out.println("T"+ finalI +" end!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    s.release();
                }
            }).start();
        }
    }
}
